package org.example.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.dto.*;
import org.example.service.CurriculumPlanService;
import org.example.service.CurriculumService;
import org.example.service.TestService;
import org.example.utils.JsonUtils;
import org.example.utils.Sort;
import org.example.vo.CurriculumPlanVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Rongchang Wu
 */
@Controller
public class SortCourseController {
    @Resource
    CurriculumPlanService service;
    /**
     * 获取课程计划
     *
     * @param resp  应答对象
     * @param page  页码
     * @param limit 每页数量
     * @throws IOException
     */
    @GetMapping("/getCurriculumPlan")
    @ResponseBody
    public void getCurriculumPlan(HttpServletResponse resp, Integer page, Integer limit) throws IOException {
        System.out.println("进入controller");
        Page<Object> obj = PageHelper.startPage(page, limit);//分页
        List<CurriculumPlanDto> curriculumPlanList = service.queryAllCurriculumPlan();
        System.out.println("进入controller1");
        for (int i = 0; i < curriculumPlanList.size(); i++) {//循环设置前端学期显示
            String schoolYearTemp = curriculumPlanList.get(i).getSchoolYear();
            String schoolYear = schoolYearTemp + "-" + (Integer.parseInt(schoolYearTemp) + 1) + "-";
            String semester = curriculumPlanList.get(i).getSemester();
            curriculumPlanList.get(i).setSemester(schoolYear + semester);
        }
        Integer count = service.count();
        //以上从service获取课程计划信息，返回给curriculumPlanList；获取总数量返回给count


        JsonUtils.customJson(resp, curriculumPlanList, count);
    }

    /**
     * 获取课程计划名对应的课程计划信息
     *
     * @param curriculumPlanId 课程计划号
     * @return 课程计划信息
     */
    @GetMapping("/getCurriculumPlanById")
    @ResponseBody
    public CurriculumPlanDto getCurriculumPlanById(Integer curriculumPlanId) {
        CurriculumPlanDto curriculumPlan = service.queryCurriculumPlanNameById(curriculumPlanId);
        System.out.println(curriculumPlan);
        //以上把系别、专业前缀去掉
        //以上service根据课程计划名找id，在根据id找到课程计划信息

        return curriculumPlan;
    }

    /**
     * 根据学年和学期获取响应的课程计划
     *
     * @param resp       应答对象
     * @param schoolYear 用户选择的学年
     * @param semester   用户选择的学期
     * @param page       页码
     * @param limit      每页数量
     * @throws IOException
     */
    @GetMapping("/getCurriculumPlanBySchoolYearAndSemester")
    @ResponseBody
    public void getCurriculumPlanBySchoolYearAndSemester(HttpServletResponse resp, String schoolYear, String semester, Integer page, Integer limit) throws IOException {
        Page<Object> obj = PageHelper.startPage(page, limit);//分页
        Integer count = service.countCurriculumPlanBySchoolYearAndSemester(schoolYear, semester);
        List<CurriculumPlanDto> curriculumPlanList = new ArrayList<>();

        CurriculumPlanDto c2 = new CurriculumPlanDto();
        c2.setCurriculumPlanName("软件工程系软件工程专业课程计划2");
        c2.setSemester("2021-2022-2");
        c2.setDepartment("软件工程2");
        c2.setMajor("软件工程2");
        c2.setCurriculumName("概率论与数理统计2");
        curriculumPlanList.add(c2);
        //以上根据学年、学期从service获取课程计划信息，curriculumPlanList

        JsonUtils.customJson(resp, curriculumPlanList, count);
    }


    /**
     * 删除课程计划
     *
     * @param curriculumPlanId 课程计划号
     * @return 删除状态
     */
    @GetMapping(value = "/deleteCurriculumPlan", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String deleteCurriculumPlan(String curriculumPlanId) {
        System.out.println("=====================id = " + curriculumPlanId);
        Integer status = 0;
        String[] ids = curriculumPlanId.split(",");
        for (int i = 0; i < ids.length; i++) {
            status += service.deleteCurriculumPlan(Integer.parseInt(ids[i]));
        }
        //以上service根据id删除课程计划，返回结果给status

        return status > 0 ? "success" : "error";
    }

    /**
     * 添加课程计划
     *
     * @param curriculumPlan 新增的课程计划
     * @return 添加状态
     */
    @GetMapping(value = "/addCurriculumPlan", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String addCurriculumPlan(CurriculumPlanVo curriculumPlan) {
        System.out.println(curriculumPlan);
        //调用service给课程计划赋值一个课程计划号id
        String curriculumId = curriculumPlan.getCurriculumId();
        String[] curriculumIds = curriculumId.split(",");
        String curriculumName = "";
        for (int i = 0; i < curriculumIds.length; i++) {
            curriculumName += service.queryCurriculumById(Integer.parseInt(curriculumIds[i])).getCurriculumName();
            curriculumName += ",";
        }
        curriculumPlan.setCurriculumName(curriculumName.substring(0, curriculumName.length() - 1));
        //以上根据课程号查找课程名
        Integer status = service.addCurriculumPlan(curriculumPlan);
        //以上service调用方法把curriculumPlan添加到数据库

        return status > 0 ? "success" : "error";
    }

    /**
     * 更新的课程计划
     *
     * @param curriculumPlan 修改的课程计划信息
     * @return 修改状态
     */
    @GetMapping(value = "/editCurriculumPlan", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String editCurriculumPlan(CurriculumPlanVo curriculumPlan) {
        System.out.println(curriculumPlan);
        curriculumPlan.setDepartment(curriculumPlan.getDepartment().substring(1));
        curriculumPlan.setMajor(curriculumPlan.getMajor().substring(1));
        Integer status = service.updateCurriculumPlan(curriculumPlan);
        //以上service调用方法把获取curriculumPlan并设置id，更新数据

        return status > 0 ? "success" : "error";
    }

    /**
     * 根据curriculumName获取课程信息/获取全部的课程信息
     *
     * @param curriculumName 课程名
     * @param page           页码
     * @param limit          每页数量
     * @param resp           应答对象
     * @throws IOException
     */
    @GetMapping("/getCurriculumList")
    @ResponseBody
    public void getCurriculumList(String curriculumName, Integer page, Integer limit, HttpServletResponse resp) throws IOException {
        String json = "{}";
        ObjectMapper om = new ObjectMapper();
        Integer count = service.countCurriculum();
        if (curriculumName == null) {
            Page<Object> obj = PageHelper.startPage(page, limit);
            List<GiveInstructionDto> curriculumList = service.queryAllGiveInstruction();
            json = om.writeValueAsString(curriculumList);
        } else {
            Page<Object> obj = PageHelper.startPage(page, limit);
            List<GiveInstructionDto> curriculumList = service.queryCurriculumByName(curriculumName);
            json = om.writeValueAsString(curriculumList);
            count = curriculumList.size();
        }

        json = "{\"code\":0,\"msg\":\"\",\"count\":" + count + ",\"data\":" + json + "}";
        System.out.println(json);

        PrintWriter out = resp.getWriter();
        resp.setContentType("application/json;charset=utf-8");
        out.write(json);
        out.flush();
        out.close();
    }
    @GetMapping("/sortCurriculum")
    public void sortCurriculum(){
        Sort s=new Sort();
        s.main();
    }

}
